<template>
  <div class="app-container">
    <div class="dashboard-welcome">
      <div class="welcome-left">
        <h2>{{ greetingText }}</h2>
        <p class="welcome-desc">欢迎使用货物监控系统，今天是 {{ today }}，祝您工作顺利！</p>
      </div>
      <div class="welcome-right">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          <span>刷新数据</span>
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6" v-for="card in statCards" :key="card.title">
        <div class="data-card" :class="card.type">
          <div class="card-body">
            <div class="card-value">{{ card.value }}</div>
            <div class="card-title">{{ card.title }}</div>
          </div>
          <div class="card-icon">
            <el-icon><component :is="card.icon"></component></el-icon>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover" class="box-card">
          <template #header>
            <div class="card-header">
              <span>最近货物记录</span>
              <router-link to="/shipment/list">
                <el-button link type="primary">查看更多</el-button>
              </router-link>
            </div>
          </template>
          <el-table v-loading="loading" :data="recentShipments" style="width: 100%">
            <el-table-column prop="number_no" label="货物单号" min-width="180" />
            <el-table-column prop="pickup_warehouse" label="取货仓库" min-width="120" />
            <el-table-column prop="delivery_warehouse" label="卸货仓库" min-width="120" />
            <el-table-column prop="mac_id" label="设备号" min-width="120" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <router-link :to="`/shipment/detail/${scope.row.id}`">
                  <el-button type="primary" link>详情</el-button>
                </router-link>
                <router-link :to="`/shipment/route/${scope.row.id}`">
                  <el-button type="success" link>路线</el-button>
                </router-link>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="8">
        <el-card shadow="hover" class="box-card system-status-card">
          <template #header>
            <div class="card-header">
              <span>系统状态</span>
              <el-tag type="success" v-if="systemStatus.allRunning">运行正常</el-tag>
              <el-tag type="danger" v-else>部分异常</el-tag>
            </div>
          </template>
          <div class="system-status-list">
            <div class="status-item" v-for="(item, index) in systemStatus.components" :key="index">
              <div class="status-info">
                <span class="status-name">{{ item.name }}</span>
                <span class="status-desc">{{ item.description }}</span>
              </div>
              <div class="status-indicator">
                <el-tag :type="item.status ? 'success' : 'danger'" size="small">
                  {{ item.status ? '正常' : '异常' }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getShipments } from '@/api/shipment'
import { getApiConfigs } from '@/api/config'
import { Refresh, Tickets, Van, Link, Setting } from '@element-plus/icons-vue'

const userStore = useUserStore()
const loading = ref(false)
const recentShipments = ref([])

// 统计卡片数据
const statistics = ref({
  totalShipments: 0,
  activeShipments: 0,
  apiConfigCount: 0,
  warningCount: 0
})

// 系统状态
const systemStatus = ref({
  allRunning: true,
  components: [
    { name: '后端服务', description: 'API服务运行状态', status: true },
    { name: '定时任务', description: 'Celery任务执行情况', status: true },
    { name: '数据库', description: 'PostgreSQL连接状态', status: true },
    { name: '外部API', description: '第三方API连接状态', status: true }
  ]
})

// 统计卡片
const statCards = computed(() => [
  {
    title: '货物总数',
    value: statistics.value.totalShipments,
    icon: 'Tickets',
    type: 'primary'
  },
  {
    title: '运输中',
    value: statistics.value.activeShipments,
    icon: 'Van',
    type: 'success'
  },
  {
    title: 'API配置',
    value: statistics.value.apiConfigCount,
    icon: 'Link',
    type: 'info'
  },
  {
    title: '异常警告',
    value: statistics.value.warningCount,
    icon: 'Warning',
    type: 'danger'
  }
])

// 获取时段问候语
const greetingText = computed(() => {
  const hour = new Date().getHours()
  const name = userStore.userInfo?.name || '管理员'
  
  if (hour < 6) {
    return `深夜好，${name}`
  } else if (hour < 9) {
    return `早上好，${name}`
  } else if (hour < 12) {
    return `上午好，${name}`
  } else if (hour < 14) {
    return `中午好，${name}`
  } else if (hour < 18) {
    return `下午好，${name}`
  } else if (hour < 22) {
    return `晚上好，${name}`
  } else {
    return `夜深了，${name}`
  }
})

// 获取今天日期
const today = computed(() => {
  const date = new Date()
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
})

// 获取最近货物记录
const fetchRecentShipments = async () => {
  loading.value = true
  try {
    const res = await getShipments({ limit: 5 })
    if (res && res.data) {
      recentShipments.value = res.data
      statistics.value.totalShipments = res.total || res.data.length
      
      // 计算运输中的货物数量
      statistics.value.activeShipments = res.data.filter(item => 
        item.status === 'in_transit' || item.status === 'pickup'
      ).length
      
      // 计算异常警告数量
      statistics.value.warningCount = res.data.filter(item => 
        item.status === 'warning' || item.status === 'exception'
      ).length
    }
  } catch (error) {
    console.error('获取货物记录失败:', error)
    systemStatus.value.components[0].status = false
    updateSystemStatus()
  } finally {
    loading.value = false
  }
}

// 获取API配置状态
const fetchApiStatus = async () => {
  try {
    const res = await getApiConfigs({ limit: 100 })
    if (res && res.data) {
      statistics.value.apiConfigCount = res.total || res.data.length
      systemStatus.value.components[3].status = true
    }
  } catch (error) {
    console.error('获取API配置状态失败:', error)
    systemStatus.value.components[3].status = false
    updateSystemStatus()
  }
}

// 更新系统状态
const updateSystemStatus = () => {
  systemStatus.value.allRunning = systemStatus.value.components.every(component => component.status)
}

// 刷新数据
const refreshData = () => {
  fetchRecentShipments()
  fetchApiStatus()
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'waiting': 'info',
    'pickup': 'primary',
    'in_transit': 'success',
    'warning': 'warning',
    'exception': 'danger',
    'completed': ''
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'waiting': '待取货',
    'pickup': '已取货',
    'in_transit': '运输中',
    'warning': '预警',
    'exception': '异常',
    'completed': '已完成'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.dashboard-welcome {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .welcome-left {
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
    }
    
    .welcome-desc {
      color: #606266;
      margin: 0;
    }
  }
}

.data-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  }
  
  .card-body {
    .card-value {
      font-size: 28px;
      font-weight: 700;
      margin-bottom: 5px;
    }
    
    .card-title {
      color: #606266;
      font-size: 14px;
    }
  }
  
  .card-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24px;
  }
  
  &.primary {
    .card-value {
      color: #409EFF;
    }
    .card-icon {
      background-color: rgba(64, 158, 255, 0.1);
      color: #409EFF;
    }
  }
  
  &.success {
    .card-value {
      color: #67C23A;
    }
    .card-icon {
      background-color: rgba(103, 194, 58, 0.1);
      color: #67C23A;
    }
  }
  
  &.info {
    .card-value {
      color: #909399;
    }
    .card-icon {
      background-color: rgba(144, 147, 153, 0.1);
      color: #909399;
    }
  }
  
  &.danger {
    .card-value {
      color: #F56C6C;
    }
    .card-icon {
      background-color: rgba(245, 108, 108, 0.1);
      color: #F56C6C;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.system-status-list {
  .status-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .status-info {
      display: flex;
      flex-direction: column;
      
      .status-name {
        font-weight: 500;
        margin-bottom: 4px;
      }
      
      .status-desc {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.mt-20 {
  margin-top: 20px;
}
</style>